package com.mvc.finance.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mvc.business.model.OrderItem;
import com.mvc.business.service.OrderAssociatedManager;
import com.mvc.finance.model.CommercialInvoiceItem;
import com.mvc.framework.model.Auditable;
import com.mvc.framework.service.BaseService;

@Service
public class CommercialInvoiceItemManager extends BaseService<CommercialInvoiceItem, Integer> {
	@Autowired
	private OrderAssociatedManager	orderAssociatedManager;

	public List<CommercialInvoiceItem> getCommercialInvoiceItemsByCommercialInvoiceId(int commercialInvoiceId) {
		CommercialInvoiceItem example = new CommercialInvoiceItem();
		example.setCommercialInvoiceId(commercialInvoiceId);
		example.setRecStatus(Auditable.REC_STATUS_VALID);
		return getHibernateTemplate().findByExample(example);
	}

	public void deleteByCommercialInvoiceId(int commercialInvoiceId) {
		deleteByWhere("commercialInvoiceId = " + commercialInvoiceId);
	}

	public void savePackingItem(CommercialInvoiceItem orderItem, String operation) throws Exception {
		if (operation.equals("del")) {
			super.delete(orderItem.getId());
			orderAssociatedManager.saveCommercialInvoiceOrders(orderItem.getCommercialInvoiceId());
		} else if (operation.equals("add")) {
			orderItem.setId(null);
			super.save(orderItem);
		} else if (operation.equals("edit")) {
			super.save(orderItem);
		}
	}

	public void updateCommercialInvoiceId(Integer oldOrderId, Integer newOrderId) {
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		Query query = session.createQuery("update " + CommercialInvoiceItem.class.getName() + " set commercialInvoiceId = " + newOrderId
		        + " where commercialInvoiceId = " + oldOrderId);
		query.executeUpdate();
	}

	public Double getTotalPackingQuantityOfOrderItem(Integer orderItemId) {
		String sql = "select sum(A.quantity) from " + CommercialInvoiceItem.class.getName()
		        + " A  where A.orderItemId=? AND A.recStatus=? AND commercialInvoiceId>0";
		return searchObjectBySql(Double.class, sql, new Object[] { orderItemId, Auditable.REC_STATUS_VALID });
	}

	public List<Integer> getOrderIds(Integer commercialInvoiceId) {
		String sql = "select distinct (B.orderId) from " + CommercialInvoiceItem.class.getName() + " A, " + OrderItem.class.getName()
		        + " B where A.commercialInvoiceId=? AND A.recStatus=? AND A.orderItemId = B.objectId AND B.recStatus = ? ";
		return searchBySql(Integer.class, sql, new Object[] { commercialInvoiceId, Auditable.REC_STATUS_VALID, Auditable.REC_STATUS_VALID });
	}
}
